package com.cpoopc.fuckapp.utils.security;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

/**
 * maf加密模块的支持类，提供编码转换，静态常量
 * <p>
 * Description:描述
 * </p>
 */
class SecurityUtil {

	protected static final String ERROR_KEY_IS_NULL = "the key is null";
	private static final String TAG = "SecurityUtil";

	/**
	 * 将十六进制的字符串转换为byte[]数组
	 * 
	 * @param string
	 *            待转换的字符串
	 * @return byte[]数组
	 */
	protected static byte[] convertHexString(String string) {
		if (null == string || string.equals("")) {
			return null;
		}
		byte digest[] = new byte[string.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = string.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}

		return digest;
	}

	/**
	 * 将byte[]转换为十六进制字符串
	 * 
	 * @param b
	 *            待转换的byte[]
	 * @return 处理后的字符串
	 */
	protected static String toHexString(byte b[]) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String plainText = Integer.toHexString(0xff & b[i]);
			if (plainText.length() < 2)
				plainText = "0" + plainText;
			hexString.append(plainText);
		}

		return hexString.toString();
	}

	/**
	 * 从文件中读出对象，这里用于读取存在文件中的秘钥，需要注意这个方法只能用于读取只有一个秘钥的文件
	 * 
	 * @param file
	 *            存放秘钥的文件
	 * @return object对象
	 */
	protected static Object getObjFromFile(String file) {

		ObjectInputStream ois = null;
		Object obj = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			obj = ois.readObject();
		} catch (Exception e) {
			Log.w(TAG, "" + e.getMessage());
		} finally {
			try {
				ois.close();
			} catch (IOException e) {
				Log.w(TAG, "" + e.getMessage());
			}
		}
		return obj;
	}

	/**
	 * 从流中读出对象，这里用于读取存在流中的秘钥，需要注意这个方法只能用于读取一个密匙
	 * 
	 * @param is
	 *            存放秘钥的流
	 * @return object对象
	 */
	protected static Object getObjFromStream(InputStream is) {

		ObjectInputStream ois = null;
		Object obj = null;
		try {
			ois = new ObjectInputStream(is);
			obj = ois.readObject();
		} catch (Exception e) {
			Log.w(TAG, "" + e.getMessage());
		} finally {
			try {
				ois.close();
			} catch (IOException e) {
				Log.w(TAG, "" + e.getMessage());
			}
		}
		return obj;
	}

	/**
	 * 读取输入流中的数据，返回byte[]格式
	 * 
	 * @param inStream
	 *            用于转换为byte数组
	 * @return
	 * @throws IOException
	 */
	protected static byte[] getByteFromInputStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}
}
